﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace System.Controls.Extensions
{
  public static class VisualTree
  {
    public static bool IsDescendantOf( DependencyObject element, DependencyObject parent, bool popupRecurse = true )
    {
      while ( element != null )
      {
        if ( Equals( element, parent ) )
          return true;

        element = GetParent( element, popupRecurse );
      }

      return false;
    }

    private static DependencyObject GetParent( DependencyObject element, bool popupRecurse = true )
    {
      if ( popupRecurse )
      {
        var popup = element as Popup;

        if (popup != null && popup.PlacementTarget != null )
          return popup.PlacementTarget;
      }

      var visual = element as Visual;
      var parent = ( visual == null ) ? null : VisualTreeHelper.GetParent( visual );

      if ( parent != null )
        return parent;

      var fe = element as FrameworkElement;

      if ( fe != null )
      {
        parent = fe.Parent;

        if ( parent == null )
          parent = fe.TemplatedParent;

      }
      else
      {
        var fce = element as FrameworkContentElement;

        if ( fce == null )
          return null;

        parent = fce.Parent;

        if ( parent == null )
          parent = fce.TemplatedParent;

      }

      return parent;
    }


  }
}
